<template>
	<view class="page">
		<view class="live-camera">
			<view class="preview">
				<canvas type="2d" style="flex: 1;height: 100%;" canvas-id="firstCanvas" id="firstCanvas"></canvas>
			</view>

			<view class="bottom">
				<view class="cancle" @click="cancle">
					<image src="@/static/images/close_icon_1.png" mode="widthFix"></image>
				</view>
				<view class="save" @click="save">
					<image src="@/static/images/save_icon.png" mode="widthFix"></image>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	import {
		uploadToServe,
		getCurrenPage
	} from '@/common/util.js'
	import {
		getSystemInfo
	} from '@/common/promise.js'
	export default {
		data() {
			return {
				path: '',
				systemInfo: {},
				userInfo: uni.getStorageSync('userInfo'),
				resultUrl: '',
				isWatermark: '',
				params: {},
				qr_data: {}
			};
		},
		async onLoad(opt) {
			let params = JSON.parse(decodeURIComponent(opt.params));
			console.log('params', params)
			this.systemInfo = await this.getSystemInfo();
			this.params = {
				...params
			};

		},
		onReady() {
			this.addWatermack();
		},
		async onShow() {},
		// onBackPress() {
		// 	this.cancle();
		// 	return true
		// },
		methods: {

			// 获取手机系统信息
			async getSystemInfo() {
				//处理安卓手机异步授权问题 
				let res = await getSystemInfo();
				return res
			},

			/*
			地址文本超出换行
			str:要绘制的字符串
			canvas:canvas对象
			initX:绘制字符串起始x坐标
			initY:绘制字符串起始y坐标
			lineHeight:字行高，自己定义个值即可  
			*/
			canvasTextAutoLine(str, ctx, initX, initY, lineHeight) {
				// var ctx = uni.createCanvasContext('firstCanvas'); 
				var lineWidth = 0;
				var canvasWidth = this.systemInfo.windowWidth - 20;
				var lastSubStrIndex = 0;
				let isWrap = false;
				let canvasHeight = this.systemInfo.windowHeight - 90;
				for (let i = 0; i < str.length; i++) {
					lineWidth += ctx.measureText(str[i]).width;
					if (lineWidth > canvasWidth - initX) { //减去initX,防止边界出现的问题
						ctx.fillText(str.substring(lastSubStrIndex, i), initX, initY);
						initY += lineHeight;
						// console.log('22222',initY,lineHeight);
						lineWidth = 0;
						lastSubStrIndex = i;
						isWrap = true;
					}
					if (i == str.length - 1) {
						ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
					}
					// console.log(initX,initY);
				}

				let len = '';
				ctx.setFillStyle('#f00');
				if (isWrap) {
					len = initY - (canvasHeight - 125) + 14;
					ctx.fillRect(10, canvasHeight - 123 - 14, 3, len);
				} else {
					len = initY - (canvasHeight - 125);
					ctx.fillRect(10, canvasHeight - 123 - 14, 3, len);
				}

			},

			/**
			 * 
			 * @param {CanvasContext} ctx canvas上下文
			 * @param {number} x 圆角矩形选区的左上角 x坐标
			 * @param {number} y 圆角矩形选区的左上角 y坐标
			 * @param {number} w 圆角矩形选区的宽度
			 * @param {number} h 圆角矩形选区的高度
			 * @param {number} r 圆角的半径
			 */
			roundRect(ctx, x, y, w, h, r) {
				// 开始绘制
				ctx.beginPath()
				// 因为边缘描边存在锯齿，最好指定使用 transparent 填充
				// 这里是使用 fill 还是 stroke都可以，二选一即可
				ctx.setFillStyle('#fff')
				// ctx.setStrokeStyle('transparent')
				// 左上角
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

				// border-top
				ctx.moveTo(x + r, y)
				ctx.lineTo(x + w - r, y)
				ctx.lineTo(x + w, y + r)
				// 右上角
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

				// border-right
				ctx.lineTo(x + w, y + h - r)
				ctx.lineTo(x + w - r, y + h)
				// 右下角
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

				// border-bottom
				ctx.lineTo(x + r, y + h)
				ctx.lineTo(x, y + h - r)
				// 左下角
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

				// border-left
				ctx.lineTo(x, y + r)
				ctx.lineTo(x + r, y)

				// 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
				ctx.fill()
				// ctx.stroke()
				ctx.closePath()
				// 剪切
				ctx.clip()
			},

			addWatermack() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let {
					windowWidth: w,
					windowHeight: h,
					statusBarHeight
				} = this.systemInfo;
				let {
					time,
					weather,
					location,
					address,
					qr_path,
					path
				} = this.params;
				let canvasHeight = h - 90;
				let _this = this;
				let ctx = uni.createCanvasContext('firstCanvas'); /** 创建画布 */
				ctx.drawImage(path, 0, 0, w, canvasHeight);

				this.drawTips({
					ctx,
					time,
					weather,
					location,
					canvasHeight
				});

				this.canvasTextAutoLine('地点：' + address, ctx, 20, canvasHeight - 50, 14);

				this.roundRect(ctx, w - 85, statusBarHeight + 10, 80, 97, 5);
				this.drawText(ctx, '扫码导航', w - 85, w - 10, statusBarHeight + 100);
				ctx.drawImage(qr_path, w - 80, statusBarHeight + 15, 70, 70);


				ctx.draw(true, (() => {
					setTimeout(() => { //合成延迟
						uni.canvasToTempFilePath({
							canvasId: 'firstCanvas',
							// fileType: 'jpg',
							success(res) {
								_this.path = res.tempFilePath;
							},
							fail(e) {
								console.log('fail', e);
							},
							complete() {
								uni.hideLoading();
							}
						})
					}, 1000);
				})());
			},

			drawTips({
				ctx,
				time,
				weather,
				location,
				canvasHeight
			}) {

				ctx.setFontSize(14);
				ctx.setFillStyle('#fff'); //水印颜色
				// 130
				time && ctx.fillText('时间：' + time, 20, canvasHeight - 125);
				weather && ctx.fillText('天气：' + weather, 20, canvasHeight - 100);
				location && ctx.fillText('经纬度：' + location, 20, canvasHeight - 75);
			},

			drawText(ctx, str, sx, ex, y) {

				let lineWidth = 0;
				ctx.setFontSize(12);
				for (let i = 0; i < str.length; i++) {
					lineWidth += ctx.measureText(str[i]).width;
				}

				let x = (80 - lineWidth) / 2;
				ctx.setFillStyle('#000')
				// console.log(lineWidth, x, str);
				ctx.fillText(str, sx + x, y)
			},


			save: async function() {

				this.$store.commit('UPDATE_UPLOAD_STATE', true)
				getApp().globalData.upload_img = this.path;
				uni.navigateBack({
					delta: 2
				})


				// // 上传现场照片
				// let _this = this;
				// let res = await this.$api.user_api.getToken({
				// 	appid: '100002',
				// 	appsecret: '24dcb652ce0043c9a53d90de2468b5b8'
				// })
				// console.log(res)
				// uni.showLoading({
				// 	mask: true,
				// 	title: '图片识别中'
				// })

				// uploadToServe({
				// 	type: 1,
				// 	url: 'https://shibie.honghuoyi.com/user/sb-insert.do',
				// 	filePath: this.path,
				// 	name: 'myfile',
				// 	formData: {
				// 		appid: 100002,
				// 		token: res.data.data.token,
				// 		uid: this.userInfo.id
				// 	}
				// }).then((up_res) => {
				// 	console.log(up_res)
				// 	uni.hideLoading();
				// 	if (up_res.ret == 1000) {
				// 		this.resultUrl = 'https://shibie.honghuoyi.com/image/sb-image.do?path=' + up_res.data;
				// 		console.log(this.resultUrl)
				// 	}
				// })
			},


			cancle: function() {
				// uni.redirectTo({
				// 	url: '/package_shibie/camera/camera'
				// })
				uni.navigateBack({
					delta: 2
				});
			},

		}
	};
</script>
<style lang="scss">
	.page {
		height: 100%;
	}

	.live-camera {
		height: 100%;

		.preview {
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;
			z-index: 1;
			width: 100%;
			height: calc(100% - 90px);

			image {
				width: 100%;
			}
		}

		#cutImage {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background: #f00;
		}

		.bottom {
			position: absolute;
			left: 0;
			bottom: 0;
			width: 80%;
			padding: 0 10%;
			height: 90px;
			z-index: 98;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #000;
			box-sizing: inherit;

			.cancle,
			.save {
				width: 90rpx;
				height: 90rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.cancle {
				color: #fff;
				font-size: 34rpx;

				image {
					width: 50%;
				}
			}

			.link {
				color: #fff;
				font-size: 34rpx;
			}

			.save {
				image {
					width: 60%;
				}
			}
		}
	}
</style>
